package cn.bookCity.daoimpl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.bookCity.Exception.MyException;
import cn.bookCity.dao.OrderDao;
import cn.bookCity.domain.Orders;
import cn.bookCity.domain.Products;
import cn.bookCity.util.DataSourceUtil;

public class OrderDaoImpl implements OrderDao {

	@Override
	public void insertOrder(Orders order) {
		QueryRunner qr=new QueryRunner(DataSourceUtil.getDataSource());
		try {
			String sql="insert into orders values (?,?,?,?,?,0,?,?)";
			qr.update(sql,order.getId(),order.getMoney(),order.getReceiverAddress(),order.getReceiverName(),order.getReceiverPhone(),order.getOrdertime(),order.getUser().getId());
		}catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}

	@Override
	public int getCount(String uid) {
		QueryRunner qr=new QueryRunner(DataSourceUtil.getDataSource());
		try {
			String sql="select count(id) from orders where user_id=?";
			Object obj = qr.query(sql, new ScalarHandler(),uid);
			return Integer.parseInt(obj.toString());
		}catch (SQLException e) {
		   e.printStackTrace();
		}
		return 0;
	}

	@Override
	public List<Orders> getPageOrders(int startNo, int pagesize,String uid) {
		QueryRunner qr=new QueryRunner(DataSourceUtil.getDataSource());
		try {
			String sql="select *from orders where user_id=? order by ordertime desc limit ?,?";
			return qr.query(sql, new BeanListHandler<>(Orders.class),uid,startNo,pagesize);
		}catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<Orders> getOrders() {
		QueryRunner qr=new QueryRunner(DataSourceUtil.getDataSource());
		try {
			String sql="select *from orders";
			return qr.query(sql, new BeanListHandler<>(Orders.class));
		}catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Orders getOrdersById(String id) {
		QueryRunner qr=new QueryRunner(DataSourceUtil.getDataSource());
		try {
			String sql="select * from orders where id=?";
			return qr.query(sql, new BeanHandler<>(Orders.class),id);
		}catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	

}
